import { Component, OnInit, ViewChild, ViewContainerRef, ComponentRef, ComponentFactoryResolver, EventEmitter } from '@angular/core';
import * as flatpickr from 'flatpickr';
import { zh } from "flatpickr/dist/l10n/zh.js";
import { AppPaginationComponent, PaginationModel } from "../../../../../widgets/pagination/pagination.component";
import { environment } from "../../../../../../environments/environment";
import * as _ from "lodash";
import { InputModeService } from './input-mode.service';
import { CommitComponent } from '../../modal/commit/commit.component';
import { SubmitComponent } from '../../modal/submit/submit.component';
import { ApplyFundGroupComponent } from '../../modal/apply-fund-group/apply-fund-group.component';
import { DataService } from '../../../../../services/data.service';
import { Util } from '../../../../../common/util';
import { SelectItem } from 'primeng/components/common/api';
import { FileUploader } from "ng2-file-upload";
@Component({
  selector: 'app-input-mode',
  templateUrl: './input-mode.component.html',
  styleUrls: ['./input-mode.component.scss'],
  providers: [InputModeService]
})
export class InputModeComponent implements OnInit {
  //判断当前listData类型,默认为false，代表空白20条数据，true为查询并填充之后的数组
  public listType: any = '1';
  // 保存并提交modal
  @ViewChild("nQDIIInputSubmitModal", { read: ViewContainerRef })
  nQDIIInputSubmitModal: ViewContainerRef;
  submitComponent: ComponentRef<SubmitComponent>;
  // 适用基金组modal
  @ViewChild("applyFundGroup", { read: ViewContainerRef })
  applyFundGroup: ViewContainerRef;
  applyFundGroupComponent: ComponentRef<ApplyFundGroupComponent>;
  // lodash
  public _: any = _;
  //用于校验列表为空白10条或者查询填充列表
  public isBlank: any = true;
  // 菜单数据
  public menuData: any;
  // 菜单权限set
  public menuResourceSet: any = [];
  public dictionaryInfo: SelectItem[];		//列表项目
  // 分页列表post数据
  public postBody = {
    pageIndex: 1,
    pageSize: 50,
  }

  // 初始化定义uploader变量,用来配置input中的uploader属性
  public uploader: FileUploader = new FileUploader({});
  // 上传文件的名称
  public uploadFileName: any = "";
  // 选择文件状态
  public fileStatus = false;
  // 上传文件名
  public fileName;
  //全选按钮
  public isCheckedAll: any = false;
  //分页配置
  public listPageInfo = {
    currentPageNum: 1,
    pageSize: 50,
    totalPages: 1,
    total: 0,
    pagesShow: 5,
    startRow: 0,
    endRow: 0,
    pageList: [5, 10, 25, 50, 100]
  };
  //条目修改下拉框绑定数据
  public dataInfo: any = {
    pageIndex: 1,
    pageSize: 50,
    sItemType: '',
    sFileSource: '',
    sFileName: '',
    sFundType: [],
    sFundGroupdsZh: '',
    sFundGroupds: '',
    f1: ''
  }
  //字典值列表
  public dictionaryList: any = {
    RISK_RECORD_TYPE: [],//属性
    NX_SOURCE: [],//条款出处
    RISK_ACCOUNT_TYPE: [],//适用基金组类别
    RISK_CTRL_METHOD: [],//事中控制方法
    RISK_CONTROL_AFTER: [],//事后监控方法
    MONITOR_REMARK: [],//风险等级
    RISK_CW_CTRL: [],//是否场外系统可控
    RISK_HS_CONTROL: []//是否事中系统可控
  }
  //列表克隆数据
  public cloneList: any;
  //导入列表克隆数据
  public cloneExportList: any;
  //条目历史列表
  public listData: any = [];
  public elementShow: any = [];
  constructor(
    public resolver: ComponentFactoryResolver,
    public inputModeService: InputModeService,
    public dataService: DataService
  ) {
    // 解决附件跨域问题
    this.uploader.onAfterAddingFile = (file) => { file.withCredentials = false; };
  }

  //在指定位置新增一行
  addRow() {
    let checkedList: any = [];
    let indexList: any = [];
    _.forEach(this.listData, (item, index) => {
      indexList.push(index)
      if (item.isChecked) {
        checkedList.push(index);
      }
    })

    if (checkedList.length == 1) {
      let body: any = {
        nNdId: "",
        nSortNo: "",
        sState: "",
        nBatchNo: "",
        sValid: "",
        sItemType: "",
        sFileName: "",
        sFileSource: "",
        sFundGroupds: "",
        sFundGroupdsZh: "",
        sFundType: [],
        sState2: "",
        sBatchNo2: "",
        f1: "",
        f2: "",
        f3: "",
        f4: "",
        f5: "",
        f6: "",
        f7: "",
        f8: "",
        f9: "",
        f10: "",
        f11: "",
        f12: "",
        f13: "",
        f14: "",
        f15: "",
        f16: "",
        f17: "",
        f18: "",
        f19: "",
        f20: ""
      }
      var sortedIndex = _.sortedIndex(indexList, checkedList[0]);
      this.listData.splice(sortedIndex + 1, 0, body);
      this.elementShow = _.cloneDeep(this.listData);
      // console.log(sortedIndex)
      // console.log(checkedList[0])
      // console.log(indexList)
      // console.log(this.listData)
      // Util.loadSelect(this.dictionaryList.RISK_ACCOUNT_TYPE, 'selectpicker' + sortedIndex + 1)
      // window['$']('#selectpicker' + sortedIndex + 1).selectpicker('render');

    } else {
      window['swal']("提示", "请选择一条数据", "warning")
    }

  }
  //删除指定行
  delRow() {
    let that = this;
    let checkList: any = [];
    _.forEach(this.listData, (item: any) => {
      if (item.isChecked) {
        checkList.push(item)
      }
    })
    if (checkList.length != 0) {
      window['swal'](
        {
          type: "warning",
          showCancelButton: true,
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          closeOnConfirm: true,
          showLoaderOnConfirm: true,
          title: "提示",
          text: "<div style='max-height: 200px;overflow-y: auto;'>" + "请确认是否删除选中行" + "</div>",
          html: true
        }, function () {
          that.listData = _.filter(that.listData, (item: any) => {
            return item.isChecked == false || item.isChecked == undefined;
          })
        }
      );
    } else {
      window['swal']("提示", "请选择需要删除的行！", "warning")
    }

  }
  //修改勾选的条目
  changeCheckedInfo(field) {
    let that = this;
    _.forEach(this.listData, (item, index) => {
      if (item.isChecked) {
        switch (field) {
          case 'sItemType':
            // console.log("进了？？？")
            // console.log(that.dataInfo.sItemType)
            // item.sItemTypeZh = that.getValueByKey(that.dataInfo.sItemType, 'RISK_RECORD_TYPE')
            // console.log("出来了？？？")
            item.sItemType = that.dataInfo.sItemType;
            that.inputChange(index, item.sItemType, field, 'RISK_RECORD_TYPE')
            break;
          case 'sFileSource':
            // item.sFileSourceZh = that.getValueByKey(that.dataInfo.sFileSource, 'NX_SOURCE')
            item.sFileSource = that.dataInfo.sFileSource;
            that.inputChange(index, item.sFileSourceZh, field, 'NX_SOURCE')
            break;
          case 'sFileName':
            item.sFileName = that.dataInfo.sFileName;
            that.inputChange(index, item.sFileName, field)
            break;
          case 'sFundType':
            // window['$']('#nQDIIInputFundType' + index).selectpicker('val', that.dataInfo.sFundType);
            item.sFundType = that.dataInfo.sFundType;
            that.inputChange(index, item.sFundType, field, 'RISK_ACCOUNT_TYPE')
            console.log(item)
            break;
          case 'sFundGroupdsZh':
          
            item.sFundGroupdsZh = that.dataInfo.sFundGroupdsZh;
            console.log(item.sFundGroupdsZh)
            item.sFundGroupds = that.dataInfo.sFundGroupds;
            that.inputChange(index, item.sFundGroupdsZh, field)
            break;
          case 'f1':
            item.f1 = that.dataInfo.f1;
            that.inputChange(index, item.f1, field)
            break;
        }
      }
    })
  }

  //根据字典key查询value
  getValueByKey(key, dictionaryName) {
    let that = this;
    let info: any;
    let sFundType: any;
    switch (dictionaryName) {
      case 'RISK_RECORD_TYPE':
        info = _.filter(that.dictionaryList.RISK_RECORD_TYPE, (item: any) => {
          return item.sItemKey == key
        })
        break;
      case 'NX_SOURCE':
        info = _.filter(that.dictionaryList.NX_SOURCE, (item: any) => {
          return item.sItemKey == key
        })
        break;
      case 'RISK_ACCOUNT_TYPE':
        let sFundTypelist:any = [];
        _.forEach(key, (it, ind) => {
          let list: any = _.filter(that.dictionaryList.RISK_ACCOUNT_TYPE, (item: any) => { return item.sItemKey == it })[0].sItemValue
          
          sFundTypelist.push(list);
        })
        sFundType = sFundTypelist.join(',')
        // info = _.filter(that.dictionaryList.RISK_ACCOUNT_TYPE, (item: any) => {
        //   return item.sItemKey == key
        // })
        break;
      case 'RISK_CTRL_METHOD':
        info = _.filter(that.dictionaryList.RISK_CTRL_METHOD, (item: any) => {
          return item.sItemKey == key
        })
        break;
      case 'RISK_CONTROL_AFTER':
        info = _.filter(that.dictionaryList.RISK_CONTROL_AFTER, (item: any) => {
          return item.sItemKey == key
        })
        break;
      case 'MONITOR_REMARK':
        info = _.filter(that.dictionaryList.MONITOR_REMARK, (item: any) => {
          return item.sItemKey == key
        })
        break;
      case 'RISK_CW_CTRL':
        info = _.filter(that.dictionaryList.RISK_CW_CTRL, (item: any) => {
          return item.sItemKey == key
        })
        break;
      case 'RISK_HS_CONTROL':
        info = _.filter(that.dictionaryList.RISK_HS_CONTROL, (item: any) => {
          return item.sItemKey == key
        })
        break;
    }
    // console.log("纳尼？？")
    // console.log(info[0])
    if(dictionaryName == 'RISK_ACCOUNT_TYPE'){
      return sFundType;
    }else{
      return info[0].sItemValue;
    }
    
  }
  ngOnInit() {
    let that = this;
    // 初始化日期控件
    flatpickr.localize(zh);

    // 多选下拉框
    window['$'](".select2").select2();

    // 字典值
    this.dictionaryList = JSON.parse(localStorage.getItem("dictionaryList"));

    this.dictionaryInfo = Util.loadPrimeSelect(this.dictionaryList.RISK_ACCOUNT_TYPE);
    this.newList(10);
    this.cloneList = _.cloneDeep(this.listData)
    Util.loadSelect(this.dictionaryList.RISK_ACCOUNT_TYPE, 'selectpicker')

    //重新定义发射事件，避免多次接收
    this.dataService.nQDIIInputModelEmitter = new EventEmitter();
    this.dataService.nQDIIInputModelEmitter.subscribe((value: any) => {
      if (value) {
        switch (value) {
          case 'inputModel':
            that.dataInfo.sFundGroupdsZh = that.dataService.nQDIIFGroupInfo;
            that.dataInfo.sFundGroupds = that.dataService.nQDIIIdList;
            that.changeCheckedInfo('sFundGroupdsZh')
            window['$']('#applyFundGroup').modal('hide');
            break;
          case 'index':
            that.listData[that.dataService.nQDIIIndexId].sFundGroupdsZh = that.dataService.nQDIIFGroupInfo;
            that.listData[that.dataService.nQDIIIndexId].sFundGroupds = that.dataService.nQDIIIdList;
            window['$']('#applyFundGroup').modal('hide');
            break;
          case 'refreshInputList':
            if (that.listType == '2') {
              that.loadlist();
            } else if (that.listType == '1') {
              that.newList(10);
            } else if (that.listType == '3') {
              that.isCheckedAll = false;
              that.listData = _.cloneDeep(that.cloneExportList)
            }
            break;
        }
      }
    })
    // 权限处理
    this.dataService.initTree.subscribe((data) => {
      if (data) {
        this.menuResourceSet = [];
        this.menuResourceSet = Util.getAuthority('风控管理', '非QDII条目管理', '条目录入');
        sessionStorage.setItem('btn-NQDII', this.menuResourceSet);
      }
    })
    this.menuResourceSet = [];
    this.menuResourceSet = Util.getAuthority('风控管理', '非QDII条目管理', '条目录入');
    sessionStorage.setItem('btn-NQDII', this.menuResourceSet);
  }
  //添加空白数据进入列表
  newList(index) {
    this.listData = [];
    this.listType = '1';
    this.isBlank = true;
    for (let i = 0; i < index; i++) {
      this.listData.push({
        nNdId: "",
        nSortNo: "",
        sState: "",
        nBatchNo: "",
        sValid: "",
        sItemType: "",
        sFileName: "",
        sFileSource: "",
        sFundGroupds: "",
        sFundGroupdsZh: "",
        sFundType: [],
        sState2: "",
        sBatchNo2: "",
        f1: "",
        f2: "",
        f3: "",
        f4: "",
        f5: "",
        f6: "",
        f7: "",
        f8: "",
        f9: "",
        f10: "",
        f11: "",
        f12: "",
        f13: "",
        f14: "",
        f15: "",
        f16: "",
        f17: "",
        f18: "",
        f19: "",
        f20: ""
      })

      this.elementShow = _.cloneDeep(this.listData);
      Util.loadSelect(this.dictionaryList.RISK_ACCOUNT_TYPE, 'nQDIIInputFundType' + i)
      window['$']('#nQDIIInputFundType' + i).selectpicker('val', this.listData[i].sFundType);
    }
  }
  //添加空白数据进入elementList
  elementList(index) {
    this.elementShow = [];
    for (let i = 0; i < index; i++) {
      this.elementShow.push({
        nNdId: "",
        nSortNo: "",
        sState: "",
        nBatchNo: "",
        sValid: "",
        sItemType: "",
        sFileName: "",
        sFileSource: "",
        sFundGroupds: "",
        sFundGroupdsZh: "",
        sFundType: "",
        sState2: "",
        sBatchNo2: "",
        f1: "",
        f2: "",
        f3: "",
        f4: "",
        f5: "",
        f6: "",
        f7: "",
        f8: "",
        f9: "",
        f10: "",
        f11: "",
        f12: "",
        f13: "",
        f14: "",
        f15: "",
        f16: "",
        f17: "",
        f18: "",
        f19: "",
        f20: ""
      })
    }
  }
  // 列表全选
  checkedAll() {
    if (this.isCheckedAll) {
      // 更新为全选
      _.forEach(this.listData, item => {
        item.isChecked = true;
      });
    } else {
      // 更新为不全选
      _.forEach(this.listData, item => {
        item.isChecked = false;
      });
    }
  }
  // 列表是否全选
  ctrlCheckAll() {
    let that = this;
    let checkList = [];
    _.forEach(this.listData, item => {
      if (item.isChecked == true) {
        checkList.push(item);
      }
    })
    if (checkList.length == this.listData.length) {
      this.isCheckedAll = true;
    } else {
      this.isCheckedAll = false;
    }
  }
  // 条数分页
  sizeChange(pageSize: number) {
    if (pageSize !== this.listPageInfo.pageSize) {
      this.listPageInfo.pageSize = pageSize;
      this.loadlist();
    }
  }
  // 列表分页
  pageNavigation(currentPageNum: number) {
    this.listPageInfo.currentPageNum = currentPageNum;
    this.loadlist(this.listPageInfo.currentPageNum, this.listPageInfo.pageSize);
  }
  //展示保存并提交modal
  showModal() {
    window['$']('#reviewBack').modal('show');
  }
  //查询分页列表
  loadlist(pageNum?, pageSize?) {
    // console.log("调用了")
    let that = this;
    let listData = [];
    this.listType = '2';
    this.isCheckedAll = false;
    this.isBlank = false;
    this.dataInfo.pageIndex = pageNum ? pageNum : this.listPageInfo.currentPageNum;
    this.dataInfo.pageSize = pageSize ? pageSize : this.listPageInfo.pageSize;
    console.log(this.dataInfo)
    this.inputModeService.inputModeList(this.dataInfo).subscribe(data => {
      if (data) {
        this.listData = data.list;
        _.forEach(this.listData, it => {
          if (it.sFundType != null) {
            it.sFundType = it.sFundType.split(",");
          }
        })
        this.cloneList = _.cloneDeep(data.list)
        if(data.list.length>0){
          this.elementList(data.list.length);
        }
        console.log(data);
        this.listPageInfo.currentPageNum = data.pageNum;
        this.listPageInfo.totalPages = data.pages;
        this.listPageInfo.total = data.total;
        this.listPageInfo.startRow = data.startRow;
        this.listPageInfo.endRow = data.endRow;

      }
    })
  }
  //校验录入模式保存或者保存并提交时必填的6个字段
  proofInfo() {
    let allInfoList: any = [];
    _.forEach(this.listData, (item, index) => {
      let checkInfo: any = [];
      let checkItem: any;
      if (item.isChecked) {
        if (item.sFileSource == null || item.sFileSource == '') {
          checkInfo.push('条款出处')
        }
        if (item.sFundType == null || item.sFundType == '') {
          checkInfo.push('适用基金类别')
        }
        if (item.sItemType == null || item.sItemType == '') {
          checkInfo.push('属性')
        }
        if (item.sFileName == null || item.sFileName == '') {
          checkInfo.push('文件名称')
        }
        if (item.f1 == null || item.f1 == '') {
          checkInfo.push('内容')
        }
        if (item.sFundGroupdsZh == null || item.sFundGroupdsZh == '') {
          checkInfo.push('适用基金组')
        }
        if (checkInfo.length > 0) {
          checkItem = checkInfo.join('、');
          let math = index + 1;
          allInfoList.push('序号为' + math + '的数据' + checkItem + '字段不能为空</br>')

        }

      }
    })
    if (allInfoList.length > 0) {
      window['swal'](
        {
          type: "warning",
          confirmButtonText: "确认",
          closeOnConfirm: true,
          title: "提示",
          text: "<div style='max-height: 200px;overflow-y: auto;'>" + allInfoList.join(' ') + "</div>",
          html: true
        }, function () {

        }
      );
      return false;
    } else {
      return true;
    }
  }
  //批量录入-录入信息(保存按钮)
  save() {
    let that = this;
    let postBody: any = [];
    //用于保存时校验必填字段
    let checkList: any = [];
    let listData = _.cloneDeep(this.listData)
    if (this.proofInfo()) {
      _.forEach(listData, item => {
        let isNull: any = true;
        if (item.isChecked) {
          delete item.isChecked;
          //判断对象字段是否全部为空值
          _.forIn(item, (value, key) => {
            if (value != '' && value != null) {
              isNull = false;
            }
          })
          if (!isNull) {
            //判断选中的对象的sFundType是否为数组
            if (Array.isArray(item.sFundType)) {
              item.sFundType = item.sFundType.join(',');
            }
            postBody.push(item)
          }

        }
      })
      console.log(JSON.stringify(postBody))
      if (postBody.length == 0) {
        window['swal']("提示", "请选择需要操作的数据", "warning")
      } else {
        window['swal']({
          type: "warning",
          showCancelButton: true,
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          closeOnConfirm: false,
          showLoaderOnConfirm: true,
          title: "提示",
          text: "<div style='max-height: 200px;overflow-y: auto;'>" + "请确认是否录入选中的信息" + "</div>",
          html: true
        },
          function (isConfirm) {
            if (isConfirm) {
              that.inputModeService.save(postBody).subscribe(data => {
                if (data) {
                  window['swal']("提示", "录入信息成功", "success")
                  if (that.listType == '2') {
                    that.loadlist();
                  } else if (that.listType == '1') {
                    that.newList(10);
                  } else if (that.listType == '3') {
                    that.isCheckedAll = false;
                    that.listData = _.cloneDeep(that.cloneExportList)
                  }
                }
              })
            }
          })
      }
    }

  }
  //批量录入提交-保存提交(保存并提交按钮)
  submit() {
    let that = this;
    let postBody: any = [];
    let listData = _.cloneDeep(this.listData)
    if (this.proofInfo()) {
      _.forEach(listData, item => {
        let isNull: any = true;
        if (item.isChecked) {
          // delete item.nNdId;
          // delete item.sState;
          // delete item.sState2;
          // delete item.sBatchNo2;
          delete item.isChecked;
          // delete item.sAccountName;
          // delete item.sLatestChange;
          // delete item.sLaunchDate;
          // delete item.sCheck;
          // delete item.sCreator;
          // delete item.sCheckPerson;
          // delete item.dOprDateCondition;
          _.forIn(item, (value, key) => {
            if (value != '' && value != null) {
              isNull = false;
            }
          })
          if (!isNull) {
            //判断选中的对象的sFundType是否为数组
            if (Array.isArray(item.sFundType)) {
              item.sFundType = item.sFundType.join(',');
            }
            postBody.push(item)
          }
        }
      })
      console.log(JSON.stringify(postBody))
      if (postBody.length == 0) {
        window['swal']("提示", "请选择需要操作的数据", "warning")
      } else {
        this.showCommitModal(postBody)
      }
    }
  }
  //保存并提交modal
  showCommitModal(item) {
    // 判断组件是否已创建，如果创建先注销
    if (this.submitComponent && this.submitComponent.instance) {
      this.submitComponent.destroy();
    }
    // 动态创建组件的实例
    const submitComponent = this.resolver.resolveComponentFactory(SubmitComponent);
    this.submitComponent = this.nQDIIInputSubmitModal.createComponent(submitComponent);
    this.submitComponent.instance.InputpostBody = item;
    this.submitComponent.instance.commitType = '录入模式';
    window['$']('#nQDIIInputSubmitModal').modal('show');
  }
  //适用基金组modal
  showApplyFundGroup(index?) {
    // 判断组件是否已创建，如果创建先注销
    if (this.applyFundGroupComponent && this.applyFundGroupComponent.instance) {
      this.applyFundGroupComponent.destroy();
    }
    // 动态创建组件的实例
    const applyFundGroupComponent = this.resolver.resolveComponentFactory(ApplyFundGroupComponent);
    this.applyFundGroupComponent = this.applyFundGroup.createComponent(applyFundGroupComponent);
    if (index != null) {
      this.applyFundGroupComponent.instance.index = index;
      if (this.listData[index].sFundGroupdsZh != '' && this.listData[index].sFundGroupdsZh != null && this.listData[index].sFundGroupdsZh != undefined) {
        this.applyFundGroupComponent.instance.checkedIdList = this.listData[index].sFundGroupds.split(',');
        console.log(this.listData[index].sFundGroupds.split(','))
      }
    } else {
      this.applyFundGroupComponent.instance.modeType = 'input';
      if (this.dataInfo.sFundGroupdsZh != '' && this.dataInfo.sFundGroupdsZh != null && this.dataInfo.sFundGroupdsZh != undefined) {
        this.applyFundGroupComponent.instance.checkedIdList = this.dataInfo.sFundGroupds.split(',');
        console.log(this.dataInfo.sFundGroupds.split(','))
      }

    }

    window['$']('#applyFundGroup').modal('show');
  }
  //根据参数判断需要转义的字段
  translateByName(i: any, name: any, itemCode: any) {
    let that = this;
    let nameZh = name + 'Zh';
    // console.log(that.listData[i][name])
    // console.log(itemCode)
    if (that.listData[i][name] != '' && that.listData[i][name] != null && that.listData[i][name] != undefined) {
      this.listData[i][nameZh] = that.getValueByKey(that.listData[i][name], itemCode)
    } else {
      this.listData[i][nameZh] = '';
    }
  }
  // 修改标蓝(i为下标,value为修改后的值,name为字段名)
  inputChange(i: any, value: any, name: any, itemCode?) {
    let that = this;
    //转义

    if (itemCode != undefined) {
      this.translateByName(i, name, itemCode);
    }
    //过滤条目顺序
    if (name == 'nSortNo') {
      setTimeout(() => {
        this.listData[i].nSortNo = this.listData[i].nSortNo.replace(/[^0-9]/g, '');
      });

    }
    // 定位tr
    let index = i + 1;
    // 定位输入框和选择框
    let id = "#input-table tbody tr:nth-child(" + index + ") td div[id=" + name + "]";
    // let id2 = "#input-table tbody tr:nth-child(" + index + ") td select[name=" + name + "]";
    // 获取当前修改对象
    let item = this.cloneList[i];
    // 循环对象
    for (let key in item) {
      // 判断字段名是否相等
      if (key == name) {
        // 判断原值是否为null(后端空值返回null,前端空值为'',实际都为空,相等)
        if (item[key] == null) {
          if (value == '') {
            window['$'](id).removeClass('triangle-topleft');
          } else {
            window['$'](id).addClass('triangle-topleft');
          }
        } else {
          // 判断原值不为null,直接对比
          if (item[key] == value) {
            // console.log("触发1")
            window['$'](id).removeClass('triangle-topleft');
          } else {
            // console.log("触发2")
            window['$'](id).addClass('triangle-topleft');
          }
        }
      }
    }
  }
  // onKeyPress(event: any) {
  //   let keyCode = event.keyCode;
  //   if ((keyCode >= 48 && keyCode <= 57 || keyCode == 8 || keyCode == 46)) {
  //     event.returnValue = true;
  //     console.log('keycode:true');
  //   } else {
  //     event.returnValue = false;
  //     console.log('keycode:false');
  //   }

  // }

  // 上传文件
  // uploadFile() {
  //   let that = this;
  //   let fileItem = this.uploader.queue;
  //   let linkFundNoList = [];
  //   console.log(linkFundNoList);
  //   console.log(this.uploader.queue)
  //   window['swal']({
  //     title: "提示",
  //     text: "是否确定上传附件?",
  //     type: "warning",
  //     showCancelButton: true,
  //     closeOnConfirm: true,
  //     confirmButtonText: "确认",
  //     confirmButtonColor: "#DD6B55",
  //     cancelButtonText: "取消",
  //     html: true
  //   }, function (isConfirm) {
  //     if (isConfirm) {
  //       // 开始上传
  //       that.uploader.uploadAll();
  //     }
  //   }
  //   );

  //   // 存放已上传文件数量
  //   let uploadedFile = [];
  //   let queueCount = this.uploader.queue.length;
  //   let uploadFailedFile = [];
  //   console.log('queueCount' + queueCount)
  //   this.uploader.onSuccessItem = function (item, response, status, headers) {
  //     let responseData: any = [];
  //     if (response) {
  //       uploadedFile.push(response);
  //     }
  //     responseData = JSON.parse(response)
  //     // 返回状态码为0即为上传成功。
  //     if (responseData.code != 0) {
  //       uploadFailedFile.push(response);

  //     }
  //     if (uploadedFile.length == queueCount) {
  //       if (uploadFailedFile.length != 0) {
  //         setTimeout(() => {
  //           window["swal"]("提示", "存在上传失败文件，请检查格式", "warning");
  //         }, 200)
  //       } else {
  //         if (uploadedFile.length == that.uploader.queue.length) {
  //           window["swal"]("成功", "文件上传成功!", "success");
  //         }
  //       }
  //     }

  //   };

  // }
  // // 清除FileUploader上传队列中的所有文件
  // clearFileQueue() {
  //   this.uploader.clearQueue();
  //   this.fileStatus = false;
  //   window['$']('#uploadModal').modal('hide');
  //   window["$"]("#fileInput").val("");
  // }

  // // 显示上传modal
  showUploadModal() {
    window['$']("#uploadModel").modal('show');
  }
  // 获取上传文件的名称
  selectedFileOnChanged(event: any) {
    this.uploadFileName = event.target.value;
    this.fileStatus = true;
  }
  // 上传文件
  uploadFile() {
    let that = this;
    let reg = /[\#&*|/:"<>?]/gi;
    if (reg.test(_.last(this.uploader.queue).file.name)) {
      window["swal"]("提示", "文件名含有特殊字符!", "warning");
    } else {
      let fileItem = _.last(this.uploader.queue);
      fileItem.url = environment.server + '/pms/v1/riskmanage/data/importExcel?token=' + sessionStorage.getItem('token');
      fileItem.method = "POST";
      // 关联input框的“name”属性
      fileItem.alias = "file";
      fileItem.formData = [
        { key: "fileName", value: _.last(this.uploader.queue).file.name }
      ],
        // 添加 POST 其他参数
        this.uploader.onBuildItemForm = (item, form) => {
          _.forEach(fileItem.formData, item => {
            form.append(item.key, item.value);
          });
        };
      window['swal']({
        title: "提示",
        text: "是否确定上传 " + _.last(this.uploader.queue).file.name + " 附件?",
        type: "warning",
        showCancelButton: true,
        closeOnConfirm: false,
        confirmButtonText: "确认",
        confirmButtonColor: "#DD6B55",
        cancelButtonText: "取消",
        showLoaderOnConfirm: true,
      }, function (isConfirm) {
        if (isConfirm) {
          // 开始上传
          fileItem.upload();
          // 上传一个文件成功的回调
          fileItem.onSuccess = function (response: any, status, headers) {
            let resVal = JSON.parse(response);
            console.log(response)
            
            if (resVal.msg == "成功") {
              window["swal"]("成功", "文件上传成功!", "success");
              window['$']('#uploadModel').modal('hide');
              that.clearFileQueue();
              that.listType = '3';
              that.listData = resVal.data;
              _.forEach(that.listData, it => {
                if (it.sFundType != null) {
                  it.sFundType = it.sFundType.split(",");
                }
              })
              if(resVal.data.length>0){
                that.elementList(resVal.data.length);
              }
              
              that.cloneExportList = _.cloneDeep(resVal.data)
            } else {
              window["swal"](resVal.msg, resVal.detailMsg, "warning");
              window['$']('#uploadModel').modal('hide');
              that.clearFileQueue();
            }
          }
        }
      })
    }
  }
  //  获取上传文件的文件名
  getFileName(value) {
    // 兼容ie title不出现问题
    this.fileName = value;
  }
  // 清除FileUploader上传队列中的所有文件
  clearFileQueue() {
    this.uploader.clearQueue();
    this.fileStatus = false;
    window['$']('#fileInput').val("");
  }
  //下载导入excel模板
  downloadExcel() {
    const iframe = window['$']("<iframe id='downloadiframe'>");
    iframe.attr('style', 'display:none');
    iframe.attr('src', environment.server + '/pms/v1/riskmanage/data/downloadImportTemplate?token=' + sessionStorage.getItem('token'));
    window['$']('body').append(iframe);
    setTimeout("$('#downloadiframe').remove()", 60000);
  }
  //点击修改单元格字段状态
  changeEleStatus(index, field, type) {
    if (type == '1') {
      this.elementShow[index][field] = '1';
    } else {
      console.log("触发")
      this.elementShow[index][field] = '';
    }

  }
}
